package com.jpyl.jpMedicalTreatment.view.activity.product;


import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.forxindu.kit.box.ViewKit;
import com.jpyl.jpMedicalTreatment.R;
import com.jpyl.jpMedicalTreatment.model.ErrorMessageModel;
import com.jpyl.jpMedicalTreatment.model.OrderMessageModel;
import com.jpyl.jpMedicalTreatment.model.ResponseModel;
import com.jpyl.jpMedicalTreatment.model.RxSpf_UserModel;
import com.jpyl.jpMedicalTreatment.model.WeiXinPayModel;
import com.jpyl.jpMedicalTreatment.network.Network;
import com.jpyl.jpMedicalTreatment.network.api.ApiError;
import com.jpyl.jpMedicalTreatment.network.api.RequestApi;
import com.jpyl.jpMedicalTreatment.util.StringUtil;
import com.jpyl.jpMedicalTreatment.view.activity.BaseActivity;
import com.jpyl.jpMedicalTreatment.view.widget.LogOutDialog;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 确定订单界面
 * Created by 15697 on 2019/3/9.
 */

public class ConfirmOrderActivity extends BaseActivity {

    @BindView(R.id.tv_confirmOrder_addressee)
    TextView tvConfirmOrderAddressee;
    @BindView(R.id.tv_confirmOrder_phone)
    TextView tvConfirmOrderPhone;
    @BindView(R.id.rela_confirmOrder_title_01)
    RelativeLayout relaConfirmOrderTitle01;
    @BindView(R.id.tv_confirmOrder_title_02)
    TextView tvConfirmOrderTitle02;
    @BindView(R.id.tv_confirmOrder_address)
    TextView tvConfirmOrderAddress;
    @BindView(R.id.rela_confirmOrder_title_02)
    RelativeLayout relaConfirmOrderTitle02;
    @BindView(R.id.tv_confirmOrder_title_03)
    TextView tvConfirmOrderTitle03;
    @BindView(R.id.tv_confirmOrder_projectName)
    TextView tvConfirmOrderProjectName;
    @BindView(R.id.rela_confirmOrder_title_03)
    RelativeLayout relaConfirmOrderTitle03;
    @BindView(R.id.tv_confirmOrder_title_04)
    TextView tvConfirmOrderTitle04;
    @BindView(R.id.tv_confirmOrder_price)
    TextView tvConfirmOrderPrice;
    @BindView(R.id.rela_confirmOrder_title_04)
    RelativeLayout relaConfirmOrderTitle04;
    @BindView(R.id.tv_confirmOrder_title_05)
    TextView tvConfirmOrderTitle05;
    @BindView(R.id.tv_confirmOrder_buyCount)
    TextView tvConfirmOrderBuyCount;
    @BindView(R.id.rela_confirmOrder_title_05)
    RelativeLayout relaConfirmOrderTitle05;
    @BindView(R.id.tv_confirmOrder_title_06)
    TextView tvConfirmOrderTitle06;
    @BindView(R.id.tv_confirmOrder_totalMoney)
    TextView tvConfirmOrderTotalMoney;
    @BindView(R.id.rela_confirmOrder_title_06)
    RelativeLayout relaConfirmOrderTitle06;
    RxSpf_UserModel spfUserModel;

    String address = "", count = "", userId = "", proId = "";
    final RequestApi publicApi = Network.getRequestApi();
    private String olderId;
    private String totalPrice;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_confirm_order;
    }

    @Override
    public void afterCreate(Bundle savedInstanceState) {
        mTitleTv.setText(getString(R.string.confirmOrder));
        spfUserModel = RxSpf_UserModel.create(this);
        String name = spfUserModel.username().get();
        String phone = spfUserModel.phone().get();
        userId = spfUserModel.userId().get();
        address = getIntent().getStringExtra("address");
        String proName = getIntent().getStringExtra("name");
        String price = getIntent().getStringExtra("price");
        count = getIntent().getStringExtra("count");
        proId = getIntent().getStringExtra("proId");
        tvConfirmOrderProjectName.setText(proName);
        tvConfirmOrderAddressee.setText(name);
        tvConfirmOrderAddress.setText(address);
        tvConfirmOrderPhone.setText(phone);
        tvConfirmOrderPrice.setText(price);
        tvConfirmOrderBuyCount.setText(count);
        String total = StringUtil.mul(price, count, 2);
        tvConfirmOrderTotalMoney.setText(total);
        totalPrice = total;
    }

    @OnClick(R.id.btn_confirmOrder)
    public void onClick() {
        jpylOrder();
    }

    /**
     * 商品下单
     */
    private void jpylOrder() {

        publicApi.jpylOrder(userId, 0, "", address, proId, Integer.parseInt(count)).map(new Func1<ResponseModel<OrderMessageModel>, OrderMessageModel>() {
            @Override
            public OrderMessageModel call(ResponseModel<OrderMessageModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<OrderMessageModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                            ViewKit.showToast(ConfirmOrderActivity.this, error.getMsg());
                        } else {
                            ViewKit.showToast(ConfirmOrderActivity.this, "下单失败");
                        }
                    }

                    @Override
                    public void onNext(OrderMessageModel model) {
                        olderId = model.getOrder().getId();
                        weiXinPayDialog();
                    }
                });
    }

    public void weiXinPayDialog() {
        LogOutDialog.Builder builder = new LogOutDialog.Builder(this);
        String mag = "即将使用微信支付" + totalPrice + "元";
        LogOutDialog dialog = builder.setMessage(mag).setTitle("提示").setPositiveButton("确定", new
                DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                jpylGetWXPayInfo();
                dialog.dismiss();
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        }).create();
        dialog.setCancelable(false);
        dialog.show();
    }

    //微信预下单
    void jpylGetWXPayInfo() {

        publicApi.jpylGetWXPayInfo(olderId).map(new Func1<ResponseModel<WeiXinPayModel>,
                WeiXinPayModel>() {
            @Override
            public WeiXinPayModel call(ResponseModel<WeiXinPayModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    String msg = responseModel.getMsg();
                    throw new ApiError(responseModel.getCode(), msg);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<WeiXinPayModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                            ViewKit.showToast(ConfirmOrderActivity.this, error.getMsg() + "");
                        }
                    }

                    @Override
                    public void onNext(WeiXinPayModel model) {
                        model.setOutTradeNumber(olderId);
                        wechatPay(model);
                    }
                });
    }
}
